
<template>
  <div>
    <el-select
      v-model="name" :loading="loading" placeholder="请输入" loading-text="输入以开始模糊搜索" v-bind="$attrs" filterable :filter-method="debouncedQuerySearch" no-match-text="未查询出数据" no-data-text="未查询出数据"
      @change="select" >
      <el-option v-for="item in options" :key="item.id" :label="`${item.realname}-${item.phone}`" :value="item.id"/>
    </el-select>
  </div>
</template>
<script>
import { debounce } from 'lodash'
import { fetchList, fetchUser } from '@/api/sys/user/user'
export default {
  name: 'SystemUserSelect',
  props: {
    modelValue: {
      type: String,
      default: undefined
    }
  },
  emits: ['update:modelValue'],
  data() {
    return {
      loading: false,
      options: [],
      name: undefined,
      listQuery: {
        page: 1,
        limit: 999999
      }
    }
  },
  watch: {
    modelValue: {
      immediate: true,
      handler(val) {
        this.getUserInfo()
      }
    }
  },
  methods: {
    /**
     * 选择
     */
    select() {
      this.$emit('update:modelValue', this.name)
      this.options = []
    },
    /**
     * 获取用户列表
     */
    async  getList() {
      this.options = []
      const res = await fetchList(this.listQuery)
      this.options = res.data.data
      this.total = res.data.total
    },
    /**
     * 模糊搜索防抖
     */
    debouncedQuerySearch: debounce(function(val) {
      this.loading = true

      if (val === '') {
        return
      }
      this.listQuery.keyWords = val
      this.getList()
      this.loading = false
    }, 500),
    /**
 *编辑时回显用户信息
 */
    getUserInfo() {
      this.name = undefined
      if (this.modelValue === undefined) {
        return
      }
      fetchUser(this.modelValue).then(response => {
        if (response.data.success) {
          this.options = response.data.data
          this.name = `${response.data.data.realname}-${response.data.data.phone}`
        }
      })
    }
  }
}
</script>
<style scoped lang="scss">

</style>
